package jehc.djshi.oauth.web;

import java.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jehc.djshi.common.annotation.Auth;
import jehc.djshi.common.base.*;
import jehc.djshi.common.entity.OauthAccountEntity;
import jehc.djshi.common.util.JsonUtil;
import jehc.djshi.common.util.StringUtil;
import jehc.djshi.oauth.model.OauthFunctionInfo;
import jehc.djshi.oauth.service.OauthFunctionInfoService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jehc.djshi.oauth.model.OauthResources;
import jehc.djshi.oauth.service.OauthResourcesService;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import com.github.pagehelper.PageInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
/**
 * @Desc 授权中心资源中心
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@RestController
@RequestMapping("/oauthResources")
@Api(value = "授权中心资源中心API",tags = "授权中心资源中心API",description = "授权中心资源中心API")
public class OauthResourcesController extends BaseAction {

	@Resource
	private OauthResourcesService oauthResourcesService;

	@Resource
	private OauthFunctionInfoService oauthFunctionInfoService;

	/**
	* 查询资源中心列表并分页
	* @param baseSearch
	*/
	@ApiOperation(value="查询资源中心列表并分页", notes="查询资源中心列表并分页")
	@PostMapping(value="/list")
	@Auth(value = "/oauthResources/list",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
	public BasePage<List<OauthResources>> getOauthResourcesListByCondition(@RequestBody BaseSearch baseSearch){
		Map<String, Object> condition = baseSearch.convert();
		commonHPager(baseSearch);
		List<OauthResources> oauthResourcesList = oauthResourcesService.getOauthResourcesListByCondition(condition);
		for(OauthResources oauthResources:oauthResourcesList){
			if(!StringUtil.isEmpty(oauthResources.getCreateId())){
				OauthAccountEntity createBy = getAccount(oauthResources.getCreateId());
				if(null != createBy){
					oauthResources.setCreateBy(createBy.getName());
				}
			}
			if(!StringUtil.isEmpty(oauthResources.getUpdateId())){
				OauthAccountEntity modifiedBy = getAccount(oauthResources.getUpdateId());
				if(null != modifiedBy){
					oauthResources.setModifiedBy(modifiedBy.getName());
				}
			}
		}
		PageInfo<OauthResources> page = new PageInfo<OauthResources>(oauthResourcesList);
		return outPageBootStr(page,baseSearch);
	}

	/**
	 * 查询全部资源中心列表
	 */
	@ApiOperation(value="查询全部资源中心列表", notes="查询全部资源中心列表")
	@GetMapping(value="/all/list")
	@Auth(value = "/oauthResources/all/list",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
	public BaseResult getOauthResourcesListAll(String sysModeId){
		//采用BTree操作模式
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("sysModeId",sysModeId);
		List<BaseBTreeGridEntity> list = new ArrayList<BaseBTreeGridEntity>();
		List<OauthFunctionInfo> oauthFunctionInfoList = oauthFunctionInfoService.getOauthFunctionInfoList(condition);
		List<OauthResources> oauthResourcesList = oauthResourcesService.getOauthResourcesListAll(condition);
		for(int j = 0; j < oauthResourcesList.size(); j++){
			OauthResources oauthResources = oauthResourcesList.get(j);
			BaseBTreeGridEntity baseBTreeGridEntity = new BaseBTreeGridEntity();
			baseBTreeGridEntity.setId(oauthResources.getId());
			baseBTreeGridEntity.setPid(oauthResources.getParentId());
			baseBTreeGridEntity.setText(oauthResources.getName());
			baseBTreeGridEntity.setLeaf(oauthResources.getLeaf()==0?false:true);
			baseBTreeGridEntity.setVueIcon(oauthResources.getComponentIcon());
			baseBTreeGridEntity.setTempObject("Sources");
			list.add(baseBTreeGridEntity);
		}
		for(int i = 0; i < oauthFunctionInfoList.size(); i++){
			OauthFunctionInfo oauthFunctionInfo = oauthFunctionInfoList.get(i);
			BaseBTreeGridEntity baseBTreeGridEntity = new BaseBTreeGridEntity();
			baseBTreeGridEntity.setId(oauthFunctionInfo.getId());
			baseBTreeGridEntity.setPid(oauthFunctionInfo.getResourcesId());
			baseBTreeGridEntity.setText(oauthFunctionInfo.getName());
			baseBTreeGridEntity.setIcon("/deng/images/icons/target_point.png");
			baseBTreeGridEntity.setLeaf(true);
			baseBTreeGridEntity.setTempObject("Function");
			baseBTreeGridEntity.setContent(""+oauthFunctionInfo.getName());
			baseBTreeGridEntity.setIntegerappend(oauthFunctionInfo.getIsAuthority()+","+oauthFunctionInfo.getIsFilter());
			list.add(baseBTreeGridEntity);
		}
		return outStr(BaseBTreeGridEntity.buildTreeF(list));
	}

	/**
	* 查询单个资源中心
	* @param {id}
	*/
	@ApiOperation(value="查询单个资源中心", notes="查询单个资源中心")
	@GetMapping(value="/get/{id}")
	@Auth(value = "/oauthResources/get",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
	public BaseResult<OauthResources> getOauthResourcesById(@PathVariable("id")String id){
		OauthResources oauthResources = oauthResourcesService.getOauthResourcesById(id);
		if(!StringUtil.isEmpty(oauthResources.getParentId())){
			OauthResources resources = oauthResourcesService.getOauthResourcesById(oauthResources.getParentId());
			if(null != resources){
				oauthResources.setParentName(resources.getName());
			}
		}

		return outDataStr(oauthResources);
	}

	/**
	* 添加
	* @param oauthResources 
	*/
	@PostMapping(value="/add")
	@ApiOperation(value="创建单个资源中心", notes="创建单个资源中心")
	public BaseResult addOauthResources(@RequestBody OauthResources oauthResources){
		int i = 0;
		if(null != oauthResources){
			i=oauthResourcesService.addOauthResources(oauthResources);
		}
		if(i>0){
			return outAudStr(true);
		}else{
			return outAudStr(false);
		}
	}

	/**
	* 修改
	* @param oauthResources 
	*/
	@PutMapping(value="/update")
	@ApiOperation(value="编辑单个资源中心", notes="编辑单个资源中心")
	public BaseResult updateOauthResources(@RequestBody OauthResources oauthResources){
		int i = 0;
		if(null != oauthResources){
			i=oauthResourcesService.updateOauthResources(oauthResources);
		}
		if(i>0){
			return outAudStr(true);
		}else{
			return outAudStr(false);
		}
	}

	/**
	* 删除
	* @param id
	*/
	@DeleteMapping(value="/delete")
	@ApiOperation(value="删除资源中心", notes="删除资源中心")
	public BaseResult delOauthResources(String id){
		int i = 0;
		if(!StringUtil.isEmpty(id)){
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("id",id.split(","));
			i=oauthResourcesService.delOauthResources(condition);
		}
		if(i>0){
			return outAudStr(true);
		}else{
			return outAudStr(false);
		}
	}

	/**
	 * 查询全部资源中心（树列表）
	 * @param request
	 */
	@ApiOperation(value="查询全部资源中心（树列表）", notes="查询全部资源中心（树列表）")
	@GetMapping(value="/bZTree")
	@Auth(value = "/oauthResources/bZTree",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
	public BaseResult getOauthResourcesBZTree(HttpServletRequest request){
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("sysModeId",request.getParameter("sysModeId"));
		String expanded = request.getParameter("expanded");
		String singleClickExpand = request.getParameter("singleClickExpand");
		List<BaseZTreeEntity> list = new ArrayList<BaseZTreeEntity>();
		List<OauthResources> oauthResourcesList = oauthResourcesService.getOauthResourcesListAll(condition);
		for(int i = 0; i < oauthResourcesList.size(); i++){
			OauthResources oauthResources = oauthResourcesList.get(i);
			BaseZTreeEntity baseZTreeEntity = new BaseZTreeEntity();
			baseZTreeEntity.setId(oauthResources.getId());
			baseZTreeEntity.setPId(oauthResources.getParentId());
			baseZTreeEntity.setText(oauthResources.getName());
			baseZTreeEntity.setName(oauthResources.getName());
			baseZTreeEntity.setIcon("/deng/images/icons/target_point.png");
//			if("0".equals(oauthResources.getResources_leaf())){
//				baseZTreeEntity.setHasLeaf(false);
//			}else{
//				baseZTreeEntity.setHasLeaf(true);
//			}
			if(("true").equals(expanded)){
				baseZTreeEntity.setExpanded(true);
			}else{
				baseZTreeEntity.setExpanded(false);
			}
			if("true".equals(singleClickExpand)){
				baseZTreeEntity.setSingleClickExpand(true);
			}else{
				baseZTreeEntity.setSingleClickExpand(false);
			}
			list.add(baseZTreeEntity);
		}
		BaseZTreeEntity baseZTreeEntity = new BaseZTreeEntity();
		List<BaseZTreeEntity> baseZTreeEntityList = baseZTreeEntity.buildTree(list,"0");
		String json = JsonUtil.toFastJson(baseZTreeEntityList);
		return outStr(json);
//		return outStr(BaseZTreeEntity.buildTree(list,false));
	}

	/**
	 * 判断菜单下面是否有功能
	 * @param oauthFunctionInfoList
	 * @param id
	 * @return
	 */
	public boolean hasLeaf(List<OauthFunctionInfo> oauthFunctionInfoList,String id){
		boolean flag = false;
		for(int i = 0; i < oauthFunctionInfoList.size(); i++){
			if(oauthFunctionInfoList.get(i).getResourcesId().equals(id)){
				return true;
			}
		}
		return flag;
	}

	/**
	 * 设置为一级资源
	 * @param id
	 * @return
	 */
	@GetMapping(value="/chMenuInfo")
	@ApiOperation(value="设置为一级资源", notes="设置为一级资源")
	public BaseResult chMenuInfo(String id){
		int i = 0;
		OauthResources oauthResources = oauthResourcesService.getOauthResourcesById(id);
		if(null != oauthResources){
			oauthResources.setParentId("0");
			i = oauthResourcesService.updateOauthResources(oauthResources);
		}
		if(i>0){
			return outAudStr(true);
		}else{
			return outAudStr(false);
		}
	}

	/**
	 * 导出资源
	 * @param response
	 * @param id
	 */
	@ApiOperation(value="导出资源", notes="导出资源")
	@GetMapping(value = "/export")
	public void exportOauthResources(HttpServletResponse response, String id) {
		oauthResourcesService.exportOauthResources(response,id);
	}

	/**
	 * 导入资源
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/import")
	@ApiOperation(value="导入资源", notes="导入资源")
	public BaseResult importOauthResources(HttpServletRequest request,HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;//转型为MultipartHttpRequest：
		MultiValueMap<String, MultipartFile> multipartFileMultiValueMap =  multipartRequest.getMultiFileMap();//获取所有文件
		Iterator<Map.Entry<String, List<MultipartFile>>> iterator = multipartFileMultiValueMap.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<String, List<MultipartFile>> entry = iterator.next();
			for (MultipartFile multipartFile : entry.getValue()) {
				oauthResourcesService.importOauthResources(request,response,multipartFile);
			}
		}
		return BaseResult.success();
	}
}
